#include "StdAfx.h"
#include "qihmessagewndclass.h"
#include "qihmessagewindow.h"

QihMessageWndClass::QihMessageWndClass()
{

}

QihMessageWndClass::~QihMessageWndClass()
{
	if(_hInstance) destroy();
}

bool QihMessageWndClass::create( HINSTANCE hInstance /*= NULL*/ )
{
	assert(_hInstance == NULL);
	assert(_name == "");

	// create unique window class name
	QUuid uid = QUuid::createUuid();
	_name = QString("Message.%s").arg(uid.toString());

	// set (or get default) instance handle
	_hInstance = hInstance;
	if(_hInstance == NULL)
		_hInstance = ::GetModuleHandle(NULL);

	// register window class
	WNDCLASSEX wce;
	memset(&wce, 0, sizeof(wce));
	wce.cbSize = sizeof(wce);
	wce.hInstance = _hInstance;
	wce.lpszClassName = _name.toStdWString().c_str();
	wce.lpfnWndProc = MessageWndProc; // static method
	return ::RegisterClassEx(&wce) != 0;
}

bool QihMessageWndClass::destroy()
{
	bool result = ::UnregisterClass(_name.toStdWString().c_str(), _hInstance) != 0;
	_hInstance = NULL;
	_name = "";
	return result;
}

QMap<HWND, QihMessageWindow*> g_windows;	// TODO: MessageWindowManager?

LRESULT CALLBACK QihMessageWndClass::MessageWndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
	//TODO: singleton?
	// QihMessageWindow* window = findWindowByHandle(hwnd);
	// if(window) 
	//		window->dispatchMessage(message, wparam, lparam);
	// else
	return ::DefWindowProc(hwnd, message, wparam, lparam);
}

QihMessageWindow* QihMessageWndClass::createWindow()
{
	QihMessageWindow* window = new QihMessageWindow(*this);
	_windows.append(window);	//TODO: singleton?
	return window;
}